<template>
  <div class="container-fluid">
    <TopBar></TopBar>

    <div class="box">

      <div class="mb-3" style="display: flex;justify-content: space-between;">
        <button type="button" @click="programAdd()" class="btn  btn-outline-success  btn-sm">
          新增项目+
        </button>

        <p class="save-pro" v-show="saveShow" @click="goToSavePro()">检测到上次还未编辑完成的项目,点击可继续编辑</p>
        <button type="button" @click="programSave()" class="btn btn-outline-light btn-sm">
          保存项目
        </button>
        <button type="button" @click="programPull(programStore.editProgram.program_id)" class="btn btn-outline-primary btn-sm">
          上传项目
        </button>
        <button type="button" @click="programDel(programStore.editProgram.program_id)"    class="btn btn-outline-danger  btn-sm" >
          删除本项目
        </button>

        <button type="button" class="btn btn-outline-light  btn-sm dropdown-toggle" data-bs-toggle="dropdown"
          aria-expanded="false">
          修改已有项目
        </button>

        <ul class="dropdown-menu">
          <div v-for=" program in programStore.programList">
            <li>
              <button class="dropdown-item" @click="programEdit(program.program_id)">{{ program.title }}</button>
            </li>
          </div>

        </ul>

      </div>

      <div class="input-group mb-3">
        <span class="input-group-text">标题</span>
        <input type="text" v-model="programStore.editProgram.title" class="form-control" placeholder="Title"
          aria-describedby="basic-addon1">
      </div>

      <div class="input-group mb-3">
        <span class="input-group-text">简介</span>
        <textarea class="form-control" v-model="programStore.editProgram.introduction"
          aria-label="With textarea"></textarea>
      </div>

      <div class="input-group mb-3">
        <span class="input-group-text">项目主图</span>
        <img style="width: 200px; border-radius: 5px;" v-if="programStore.editProgram.main_img.length > 10"
          :src="programStore.editProgram.main_img" />
        <input style="margin: auto;" type="file" ref="mainImageREF" @change="uploadFile('main', 'main', $event)"
          class="form-control" aria-describedby="inputGroupFileAddon04">
      </div>

      <p class="h3" style="color: aliceblue;">项目进展：</p>
      <div class="accordion mb-3" v-for="process in programStore.editProgram.process_list" :key="process.process_id">
        <div class="accordion-item">
          <h2 class="accordion-header" :id="'heading-' + process.process_id">
            <button class="accordion-button" type="button" data-bs-toggle="collapse"
              :data-bs-target="'#collapse-' + process.process_id" :aria-controls="'collapse-' + process.process_id">
              <code>{{ process.create_time }}</code> &nbsp;&nbsp;&nbsp; {{ process.title }}
            </button>
          </h2>
          <div :id="'collapse-' + process.process_id" class="accordion-collapse collapse"
            :aria-labelledby="'heading-' + process.process_id" data-bs-parent="#accordionExample">
            <div class="accordion-body">
              <div class="input-group mb-3">
                <span class="input-group-text" id="basic-addon1">标题</span>
                <input type="text" class="form-control" v-model="process.title" placeholder="Title"
                  aria-describedby="basic-addon1">
              </div>

              <div class="input-group mb-3">
                <span class="input-group-text">简介</span>
                <textarea class="form-control" v-model="process.introduce"></textarea>
              </div>

              <div class="input-group mb-3 imgs-pull">
                <div class="upload-btn">
                  <img style="width: 100px;height:100px;margin:auto" v-if="process.imgs[0].length > 10"
                    :src="process.imgs[0]" />

                  <input type="file" @change="uploadFile(process.process_id, 'img0', $event)" />

                  <span v-if="process.imgs[0].length < 10">图1</span>
                </div>
                <div class="upload-btn">

                  <img style="width: 100px;height:100px;margin:auto" v-if="process.imgs[1].length > 10"
                    :src="process.imgs[1]" />
                  <input type="file" @change="uploadFile(process.process_id, 'img1', $event)" />
                  <span v-if="process.imgs[1].length < 10">图2</span>

                </div>
                <div class="upload-btn">

                  <img style="width: 100px;height:100px;margin:auto" v-if="process.imgs[2].length > 10"
                    :src="process.imgs[2]" />
                  <input type="file" @change="uploadFile(process.process_id, 'img2', $event)" />
                  <span v-if="process.imgs[2].length < 10">图3</span>
                </div>
                <div class="upload-btn">

                  <img style="width: 100px;height:100px;margin:auto" v-if="process.imgs[3].length > 10"
                    :src="process.imgs[3]" />
                  <input type="file" @change="uploadFile(process.process_id, 'img3', $event)" />
                  <span v-if="process.imgs[3].length < 10">图4</span>
                </div>
                <div class="upload-btn">

                  <img style="width: 100px;height:100px;margin:auto" v-if="process.imgs[4].length > 10"
                    :src="process.imgs[4]" />
                  <input type="file" @change="uploadFile(process.process_id, 'img4', $event)" />
                  <span v-if="process.imgs[4].length < 10">图5</span>
                </div>
              </div>

              <div class="d-grid gap-2">
                <button class="btn btn-outline-danger" @click="processDel(process.process_id)" type="button">-</button>
              </div>

            </div>
          </div>
        </div>
      </div>



      <div class="d-grid gap-2 mb-3">
        <button class="btn btn-secondary" @click="processAdd()" type="button">+</button>
      </div>
      <label for="loginFormControlInput1" class="form-label" style="color: rgb(255, 237, 42);">请先登陆再操作！！！</label>
      <div class="input-group"  id="loginFormControlInput1">
        <input type="text" v-model="loginForm.username" placeholder="用户名" class="form-control">
        <input type="password" v-model="loginForm.password" placeholder="密码" class="form-control">
        <button class="btn btn-primary" type="button" @click="login()">登陆</button>
      </div>

    </div>

    <br><br>
    <br><br>
    <BottomBar />
  </div>
</template>
<script setup lang="ts">
import { onMounted } from 'vue';
import { ProgramStore } from '../store/programs/index'
import { uploadImg } from '../api/programs/index'
import { ref, reactive } from 'vue'
import toast from '@/components/Toast/index'
// 图片id
const mainImageREF: any = ref(undefined)
const programStore = ProgramStore()
const saveShow = ref(true)
const loginForm = reactive({
  username: "",
  password: ""
})
interface Process {
  process_id: string,
  create_time?: string,
  title: string,
  introduce: string,
  imgs: string[]
}

interface editProRequestData {
  program_id: string,
  title: string,
  introduction: string,
  main_img: string,
  create_time?: string,
  process_list: Process[]
}
// 登陆
function login() {
  if (loginForm.username.length < 3 || loginForm.password.length < 4 
  || loginForm.username.length > 30 || loginForm.password.length >50){
    toast.showToast({msg:"密码或用户名错误！！！",type:"warning"})
    return
  }
  programStore.login(loginForm)
}

// 修改项目
async function programEdit(id: string) {
  if(id.length<4){
    toast.showToast({msg:"修改错误",type:"warning"})
    return
  }
  //解决异步获取后不更新问题
 await programStore.getById(id)
 await programStore.getList()
  programStore.editProgram = programStore.nowProgram
}

// 添加项目
function programAdd() {
  const pro: editProRequestData = {
    program_id: '',
    title: '',
    introduction: " ",
    main_img: "",
    process_list: []
  }
  programStore.editProgram = pro

  toast.showToast({msg:"添加成功",type:"success"})

}

// 保存项目
function programSave() {

  programStore.saveProgram = programStore.editProgram
  toast.showToast({msg:"保存成功",type:"success"})
}


//文件上传
async function uploadFile(process_id: any, fileIndex: string, event: any) {

  const file = event.target.files[0];
  let imgurl = ''

  // 上传文件
  try {
    if (file.size > 10 * 1024 * 1024) {
      console.log("文件超过10Mb");
      return;
    }
    let formData = new FormData();
    formData.append('file', file);

    let res: any = await uploadImg(formData);
    console.log(res)
    imgurl = res.data.data.url
  } catch (error) {
    // 处理错误
    toast.showToast({msg:"上传失败",type:"error"})
    console.error(error);
    return
  }

  if (fileIndex === 'main') {
    programStore.editProgram.main_img = imgurl
    toast.showToast({msg:"上传成功",type:"success"})
    return
  }

  // 填充数据
  const processIndex: any = programStore.editProgram.process_list.findIndex(p => p.process_id === process_id);
  console.log(processIndex)
  if (processIndex >= 0) {
    console.log(imgurl)
    switch (fileIndex) {
      case 'img0': programStore.editProgram.process_list[processIndex].imgs[0] = imgurl
        break;
      case 'img1': programStore.editProgram.process_list[processIndex].imgs[1] = imgurl
        break;
      case 'img2': programStore.editProgram.process_list[processIndex].imgs[2] = imgurl
        break;
      case 'img3': programStore.editProgram.process_list[processIndex].imgs[3] = imgurl
        break;
      case 'img4': programStore.editProgram.process_list[processIndex].imgs[4] = imgurl
        break;
    }

  }
  toast.showToast({msg:"上传成功",type:"success"})
}

//编辑保存的项目
function goToSavePro() {
  saveShow.value = !saveShow.value
  programStore.editProgram = programStore.saveProgram
  toast.showToast({msg:"加载成功",type:"success"})
}

// 上传项目
async function programPull(id : string) {
  if(id.length > 5){
   await programStore.editPro()
    toast.showToast({msg:"修改中。。。",type:"success"})
    window.location.reload();
  }
  else{
   await programStore.pullPro()
    toast.showToast({msg:"创建中。。。",type:"success"})
    window.location.reload();
  }
  
}
// 增加过程
function processAdd() {
  const process: Process = {
    process_id: getStr(),
    create_time: getTime(),
    title: "",
    introduce: "",
    imgs: ['', '', '', '', '']
  }

  programStore.editProgram.process_list.push(process)
  toast.showToast({msg:"增加成功",type:"success"})
}

// 删除过程
function processDel(process_id: any) {
  const list = programStore.editProgram.process_list
  programStore.editProgram.process_list = list.filter(
    function (item) {
      return item.process_id !== process_id;
    }
  );
  
  programStore.delProcess({"process_id":process_id})
  toast.showToast({msg:"删除成功",type:"success"})
}
//删除项目
async function programDel(program_id: any){
  if(program_id.length < 5){
    toast.showToast({msg:"删除错误！！！",type:"error"})
    return
  }
 await programStore.delPro({"program_id":program_id,"process_id_list":[]})
 await programStore.getList()
  window.location.reload();
}

// 时间获取
function getTime() {

  var currentDate = new Date();

  // 获取年份、月份、日期、小时、分钟和秒
  var year = currentDate.getFullYear();
  var month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
  var day = ("0" + currentDate.getDate()).slice(-2);
  var hours = ("0" + currentDate.getHours()).slice(-2);
  var minutes = ("0" + currentDate.getMinutes()).slice(-2);
  var seconds = ("0" + currentDate.getSeconds()).slice(-2);

  // 构建格式化后的时间字符串
  var formattedTime = year + " " + month + " " + day + " " + hours + ":" + minutes + ":" + seconds;
  return formattedTime
}

// Id生成
function getStr() {
  var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  var str = '';
  for (var i = 0; i < 10; i++) {
    var randomIndex = Math.floor(Math.random() * chars.length);
    str += chars[randomIndex];
  }

  return str;
}

onMounted(() => {
  // 判断是否存在备份
  if (programStore.saveProgram.title.length > 3) {
    saveShow.value = false
  }
})
</script>
<style lang="scss" scoped>
.container-fluid {
  background-color: $passlink-bg-color;

  .box {

    margin: auto;
    width: $passlink-center-width;
    padding: 20px;

    .save-pro {
      color: $passlink-font-color-waring;
      text-decoration-line: underline;
    }

    .save-pro:hover {
      color: $passlink-font-color-white;
      text-decoration-line: underline;
    }

    .upload-btn {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100px;
      height: 100px;
      border: 1px dashed #ccc;
      cursor: pointer;
      overflow: hidden;
      text-align: center;
    }

    .upload-btn input[type="file"] {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
      opacity: 0;
      width: 100%;
      height: 100%;
      cursor: pointer;
    }

    .upload-btn span {
      position: relative;
      z-index: 2;
    }

    .imgs-pull {
      display: flex;
      justify-content: space-around;

    }




  }
}
</style>
